<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <div class="avatar-wrapper">
          <el-avatar 
            :size="100" 
            :src="userInfo.avatar ? `http://localhost:9090/uploads/${userInfo.avatar.split('/').pop()}` : defaultAvatar"
            @click="triggerUpload"
          />
          <div class="avatar-mask" @click="triggerUpload">
            <el-icon><Camera /></el-icon>
            <span>更换头像</span>
          </div>
          <input
            ref="fileInput"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleAvatarUpload"
          >
        </div>
        <h2 class="username">{{ userInfo.username }}</h2>
        <p class="role">学生</p>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="profile-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" disabled />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" disabled />
        </el-form-item>

        <el-form-item label="院系" prop="department">
          <el-input v-model="form.department" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form
        ref="pwdFormRef"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="pwdForm.oldPassword" 
            type="password" 
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="pwdForm.newPassword" 
            type="password" 
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="pwdForm.confirmPassword" 
            type="password" 
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handlePasswordSubmit">
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'StudentProfileIndex'
}
</script>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { getUserInfo, updateProfile, updatePassword, uploadAvatar } from '@/api/student/profile'
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const userInfo = ref({})
const fileInput = ref(null)

const form = ref({
  username: '',
  name: '',
  studentId: '',
  department: '',
  email: '',
  phone: ''
})

const pwdForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入院系', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const pwdRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await getUserInfo()
    userInfo.value = data
    Object.assign(form.value, data)
  } catch (error) {
    console.error('Failed to fetch user info:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 触发文件选择
const triggerUpload = () => {
  fileInput.value.click()
}

// 处理头像上传
const handleAvatarUpload = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  
  try {
    const formData = new FormData()
    formData.append('avatar', file)
    
    const data = await uploadAvatar(formData)
    userInfo.value.avatar = data.url
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('Failed to upload avatar:', error)
    ElMessage.error('头像上传失败')
  }
}

// 提交个人信息
const handleSubmit = async () => {
  try {
    await updateProfile(form.value)
    ElMessage.success('个人信息更新成功')
    await fetchUserInfo()
  } catch (error) {
    console.error('Failed to update profile:', error)
    ElMessage.error('更新失败')
  }
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  try {
    await updatePassword(pwdForm.value)
    ElMessage.success('密码修改成功')
    pwdForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    console.error('Failed to update password:', error)
    ElMessage.error('密码修改失败')
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.profile-card {
  max-width: 800px;
  margin: 0 auto 24px;
  background: #ffffff;
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.password-card {
  max-width: 800px;
  margin: 0 auto;
  background: #ffffff;
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.profile-header {
  text-align: center;
  padding: 24px 0;
  border-bottom: 1px solid rgba(0,0,0,0.05);
  margin-bottom: 24px;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
  cursor: pointer;

  .avatar-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #fff;
    background: rgba(0,0,0,0.5);
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.3s;

    .el-icon {
      font-size: 24px;
      margin-bottom: 8px;
    }
  }

  &:hover .avatar-mask {
    opacity: 1;
  }
}

.username {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 16px 0 8px;
}

.role {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.profile-form {
  padding: 24px;
  max-width: 500px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}
</style> 